package com.demo.common.permission.login;

import com.fasterxml.jackson.core.type.TypeReference;
import com.demo.common.cache.CacheService;
import com.demo.common.exceptions.ServiceException;
import com.demo.common.utils.CacheKeyConstants;
import com.demo.common.utils.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;

import static com.demo.common.utils.CacheKeyConstants.TOKEN;

/**
 * httpServletRequest处理公用service
 */
@Component
public class RequestService {

    @Resource
    private CacheService cacheService;

    /**
     * 获取当前登录用户id
     * @return
     */
    public Integer getUserId(){
        return getTokenInfo().getUserId();
    }

    /**
     * 获取当前登录用户token（已验证token有效性）
     * @return
     */
    public String getToken(){
        return getTokenInfo().getToken();
    }

    public TokenInfo getTokenInfo(){
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes==null){
            throw new ServiceException("未获取到当前请求信息");
        }
        String token = requestAttributes.getRequest().getHeader(CommonConstants.AUTHORIZATION);
        if(StringUtils.isBlank(token)){
            throw new ServiceException("当前请求token为空");
        }
        TokenInfo tokenInfo=cacheService.getCache(CacheKeyConstants.TOKEN + token, new TypeReference<TokenInfo>() {});
        if(tokenInfo==null){
            throw new ServiceException("token不存在或已失效");
        }
        return tokenInfo;
    }

    /**
     * 校验token
     * @return 错误信息,校验成功返回null
     */
    public String checkToken(){
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes==null){
            return "未获取到当前请求信息";
        }
        String token = requestAttributes.getRequest().getHeader(CommonConstants.AUTHORIZATION);
        if(StringUtils.isBlank(token)){
            return "当前请求token为空";
        }
        TokenInfo tokenInfo=cacheService.getCache(CacheKeyConstants.TOKEN+token);
        if(tokenInfo==null){
            return "token不存在或已失效";
        }
        return null;
    }

    /**
     * 设置tokenInfo,有效期24小时
     * @param tokenInfo
     */
    public void setTokenInfo(TokenInfo tokenInfo){
        cacheService.setCacheIfAbsent(CacheKeyConstants.TOKEN+tokenInfo.getToken(),tokenInfo,60*60*24);
    }

    /**
     * 移除token
     */
    public void removeToken(){
        String token = getToken();
        cacheService.removeCache(TOKEN+token);
    }

}
